package cdc.retrofit.official.simplemockservice;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import cdc.retrofit.official.simpleservice.Contributor;
import cdc.retrofit.official.simpleservice.GitHub;
import cdc.retrofit.official.simpleservice.SimpleService;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.mock.BehaviorDelegate;
import retrofit2.mock.MockRetrofit;
import retrofit2.mock.NetworkBehavior;

/**
 * 使用{@link MockRetrofit}创建假数据的模拟服务实现的示例。 这再次使用{@ SimpleService}的GitHub服务进行模拟。
 * 
 * @author cdc
 *
 */
public class SimpleMockService {
	public static void main(String... args) throws IOException {
		// Create a very simple Retrofit adapter which points the GitHub API.
		//创建一个非常简单的指向GitHub API的Retrofit适配器
		Retrofit retrofit = new Retrofit.Builder().baseUrl(SimpleService.API_URL).build();

		// Create a MockRetrofit object with a NetworkBehavior which manages the fake
		// behavior of calls.
		//使用管理伪造的NetworkBehavior创建MockRetrofit对象通话行为。
		NetworkBehavior behavior = NetworkBehavior.create();
		MockRetrofit mockRetrofit = new MockRetrofit.Builder(retrofit).networkBehavior(behavior).build();

		BehaviorDelegate<GitHub> delegate = mockRetrofit.create(GitHub.class);
		MockGitHub gitHub = new MockGitHub(delegate);

		// Query for some contributors for a few repositories.
		//查询一些存储库的贡献者
		printContributors(gitHub, "square", "retrofit");
		printContributors(gitHub, "square", "picasso");

		// Using the mock-only methods, add some additional data.
		//使用模拟方法，添加一些额外的数据。
		System.out.println("Adding more mock data...\n");
		gitHub.addContributor("square", "retrofit", "Foo Bar", 61);
		gitHub.addContributor("square", "picasso", "Kit Kat", 53);

		// Reduce the delay to make the next calls complete faster.
		//减少延迟以使下一个呼叫更快完成。
		behavior.setDelay(500, TimeUnit.MILLISECONDS);

		// Query for the contributors again so we can see the mock data that was added.
		//再次查询贡献者，以便我们可以看到添加的模拟数据。
		printContributors(gitHub, "square", "retrofit");
		printContributors(gitHub, "square", "picasso");
	}

	private static void printContributors(GitHub gitHub, String owner, String repo) throws IOException {
		System.out.println(String.format("== Contributors for %s/%s ==", owner, repo));
		Call<List<Contributor>> contributors = gitHub.contributors(owner, repo);
		for (Contributor contributor : contributors.execute().body()) {
			System.out.println(contributor.getLogin() + " (" + contributor.getContributions() + ")");
		}
		System.out.println();
	}
}
